package utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;


public class QuotesManager {
	String stock = new String();
	String request = new String();
	String fileName = new String();
	File resultFile;
	int periodicity =-1;

	public QuotesManager(String stock, String request, String fileName, int periodicity){
		this.stock = stock;
		this.request = request;
		this.fileName = fileName;
		this.periodicity = periodicity;
	}
	
	public QuotesManager(String stock, String request, String fileName){
		this.stock = stock;
		this.request = request;
		this.fileName = fileName;
	}

	public File getResultFile(){
		return resultFile;
	}
		
	  public void getStockDataFromVendor() throws ClientProtocolException, IOException {
	    	
		    	
	    	/**
	    	 * Replace cached result if it is older than 10 minutes.
	    	 */
	    	int maxAgeMins = this.periodicity;
	        
	    	/**
	    	 * Here, we arbitrarily chose the cache file name corresponding to
	    	 * this particular web services request. Typically, however, you
	    	 * would have a unique filename corresponding to each variation of
	    	 * web services request. So, you would need to come up with a
	    	 * mapping function to map requests into filenames if you want to
	    	 * use the caching with different variations of web services requests. 
	    	 */
	    	String fileName = stock + "-"+this.fileName+"-" + "results.txt";
	    			
	        resultFile = new File(fileName);
	        
	        boolean fileExists = resultFile.exists();
	        if (!fileExists) {
		        
	            /**
	             * Salvar como arquivo texto
	             */
	        	saveMarketData();
		        String fileLocation = resultFile.getAbsolutePath();
		        System.out.println("Replaced search results older than 1 minute: " + fileLocation);

	        } else if(this.periodicity > 0){
	        	/**if(this.periodicity != -1)
	        	 * Search result found, so check to see how old it is
	        	 */
//	        	String fileLocation = resultFile.getAbsolutePath();
	        	long lastModified = resultFile.lastModified();
	        	long now = new Date().getTime();
	        	long diff = now - lastModified;
	        	float timeSecs = diff / 1000;
	        	float timeMins = timeSecs / 60;
	        	//System.out.println("Search results found, saved " + timeMins + " minutes ago: " + fileLocation);
	        	
	        	if (timeMins > maxAgeMins) {

	        		saveMarketData();
			        //System.out.println("Replaced search results older than 10 minutes: " + fileLocation);
	        	} 
	        }
	        
	  }
	  
	  private void saveMarketData() throws IOException{
      	/**
      	 * Search result does not exist, so perform query and save it to disk.
      	 */
		  	HttpClient client = new DefaultHttpClient();
		  	HttpGet method = new HttpGet(request);


		    ResponseHandler<String> responseHandler = new BasicResponseHandler();
		    String responseBody = client.execute(method, responseHandler);
		    client.getConnectionManager().shutdown();            
	        FileOutputStream fos;
	        fos = new FileOutputStream(resultFile);
	        fos.write(responseBody.getBytes());
	   }

}
